{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "mnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n",
    "\n",
    "# 每个批次的大小\n",
    "batch_size = 100\n",
    "# 计算一共有多少个批次\n",
    "n_batch = mnist.train.num_examples // batch_size\n",
    "\n",
    "\n",
    "# 初始化权值\n",
    "def weight_variable(shape):\n",
    "    initial = tf.truncated_normal(shape, stddev=0.1)  # 生成一个截断的正态分布\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "\n",
    "# 初始化偏置\n",
    "def bias_variable(shape):\n",
    "    initial = tf.constant(0.1, shape=shape)\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "\n",
    "# 卷积层\n",
    "def conv2d(x, W):\n",
    "    # x input tensor of shape '[batch,in_height,in_width,in_channles]'\n",
    "    # W filter / kernel tensor of shape [filter_height,filter_width,in_channels,out_channels]\n",
    "    # `strides[0] = strides[3] = 1`. strides[1]代表x方向的步长，strides[2]代表y方向的步长\n",
    "    # padding: A `string` from: `\"SAME\", \"VALID\"`\n",
    "    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')  # 2d的意思是二维的卷积操作\n",
    "\n",
    "\n",
    "# 池化层\n",
    "def max_pool_2x2(x):\n",
    "    # ksize [1,x,y,1]\n",
    "    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n",
    "\n",
    "\n",
    "# 定义两个placeholder\n",
    "x = tf.placeholder(tf.float32, [None, 784])  # 28*28\n",
    "y = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "# 改变x的格式转为4D的向量[batch, in_height, in_width, in_channels]`\n",
    "x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "# 初始化第一个卷积层的权值和偏置\n",
    "W_conv1 = weight_variable([5, 5, 1, 32])  # 5*5的采样窗口，32个卷积核从1个平面抽取特征\n",
    "b_conv1 = bias_variable([32])  # 每一个卷积核一个偏置值\n",
    "\n",
    "# 把x_image和权值向量进行卷积，再加上偏置值，然后应用于relu激活函数\n",
    "h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n",
    "h_pool1 = max_pool_2x2(h_conv1)  # 进行max-pooling\n",
    "\n",
    "# 初始化第二个卷积层的权值和偏置\n",
    "W_conv2 = weight_variable([5, 5, 32, 64])  # 5*5的采样窗口，64个卷积核从32个平面抽取特征\n",
    "b_conv2 = bias_variable([64])  # 每一个卷积核一个偏置值\n",
    "\n",
    "# 把h_pool1和权值向量进行卷积，再加上偏置值，然后应用于relu激活函数\n",
    "h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n",
    "h_pool2 = max_pool_2x2(h_conv2)  # 进行max-pooling\n",
    "\n",
    "# 28*28的图片第一次卷积后还是28*28（数组变小了，但是图像大小不变），第一次池化后变为14*14\n",
    "# 第二次卷积后为14*14（卷积不会改变平面的大小），第二次池化后变为了7*7\n",
    "# 进过上面操作后得到64张7*7的平面\n",
    "\n",
    "# 初始化第一个全连接层的权值\n",
    "W_fc1 = weight_variable([7 * 7 * 64, 1024])  # 上一层有7*7*64个神经元，全连接层有1024个神经元\n",
    "b_fc1 = bias_variable([1024])  # 1024个节点\n",
    "\n",
    "# 把池化层2的输出扁平化为1维\n",
    "h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\n",
    "# 求第一个全连接层的输出\n",
    "h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n",
    "\n",
    "# keep_prob用来表示神经元的输出概率\n",
    "keep_prob = tf.placeholder(tf.float32)\n",
    "h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "# 初始化第二个全连接层\n",
    "W_fc2 = weight_variable([1024, 10])\n",
    "b_fc2 = bias_variable([10])\n",
    "\n",
    "# 计算输出\n",
    "prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n",
    "\n",
    "# 交叉熵代价函数\n",
    "cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))\n",
    "\n",
    "# 使用AdamOptimizer进行优化\n",
    "train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n",
    "\n",
    "# 结果存放在一个布尔列表中\n",
    "correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))  # argmax返回一维张量中最大的值所在的位置\n",
    "\n",
    "# 求准确率\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "    for epoch in range(21):\n",
    "        for batch in range(n_batch):\n",
    "            batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "            sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.7})\n",
    "\n",
    "        acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0})\n",
    "        print(\"Iter \" + str(epoch) + \", Testing Accuracy= \" + str(acc))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
